import React, { useEffect, useState } from 'react'
import {Grid, SearchBar,IndexBar, List} from "antd-mobile"
import request from "../../api/request";
import { useDispatch } from 'react-redux';
import { setCity } from '../../store/city/citySlice';
import { useNavigate } from 'react-router-dom';

function City() {
    const dispatch=useDispatch();
    const navigate=useNavigate();
    const [searchList,setSearchList]=useState({cityList:[],hotCities:[]});
    const [isSearch,setIsSearch]=useState(false);
    const [list,setList]=useState([]);
    const onSearch=async(value)=>{
        console.log(value)
        const res=await request.get('/city/search',{params:{wd:value}})
        console.log(res.data)
        setList(res.data.data);
        setIsSearch(true)
    }
    const handleClick=(city)=>{
        dispatch(setCity(city))
        navigate(-1);
    }
    const getList=async()=>{
        const res=await request.get('/city')
        console.log(res.data.data)
        setSearchList(res.data.data)
    }
    useEffect(()=>{
        getList()
    },[])
  return (
    <div>
      <SearchBar placeholder='搜索内容' onSearch={onSearch} onClear={()=>setIsSearch(false)}></SearchBar>
      {
        isSearch ? (<div>
            <List>
                {
                    list.map((v,i)=>{
                        return <List.Item onClick={()=>handleClick(v.name)} key={i}>{v.name}</List.Item>
                    })
                }
            </List>
        </div>) : (<div>
            <h3>热门城市</h3>
            <Grid columns={4}>
                {
                    searchList.hotCities.map((v,i)=>{
                        return <Grid.Item onClick={()=>handleClick(v.name)} key={i}>{v.name}</Grid.Item>
                    })
                }
            </Grid>
            <IndexBar style={{height:"100vh"}}>
                {
                    searchList.cityList.map((v,i)=>{
                        return <IndexBar.Panel key={i} index={v.title} title={v.title}>
                            <List>
                                {
                                    v.citys.map((v,i)=>{
                                        return <List.Item onClick={()=>handleClick(v.name)} key={i}>{v.name}</List.Item>
                                    })
                                }
                            </List>
                        </IndexBar.Panel>
                    })
                }
            </IndexBar>
        </div>)
      }
    </div>
  )
}

export default City
